//
//  DatabaseManager.swift
//  ios-template
//
//  Created by lvyii000 on 2021/8/23.
//  Copyright © 2021 耳東陳. All rights reserved.
//

import RealmSwift

class RealmManager {

    static let shared = RealmManager()
    let realm = getRealm()

    func write<T: Object>(item: T) {
        realm.beginWrite()
        realm.add(item)
        try! realm.commitWrite()
    }

    func getObjects<T: Object>(type: T.Type) -> [T] {
        return realm.objects(T.self).map({ $0 })
    }

    func delete<T: Object>(item: T) {

        try! realm.write {
            realm.delete(item)
        }
    }
    
    private class func getRealm() -> Realm {
        let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
        let dbPath = docPath.appending("/defaultDB.realm")
        /// 传入路径会自动创建数据库
        let defaultRealm = try! Realm(fileURL: URL.init(string: dbPath)!)
        return defaultRealm
    }
}
